package com.app.web.goods.category;

import com.app.utils.base.j2se.Common;
import com.app.utils.base.j2se.JsonUtil;
import com.app.utils.base.j2se.Logger;
import com.app.utils.web.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description
 * Created by 王伟
 * Date create on 10:56 2019/12/5.
 */
@Service
public class CategoryManager {
    @Autowired
    private CategoryDao categoryDao;

    private static List<Category> categories;
    private static List<Map<String,Object>> childList;

    @PostConstruct
    void init(){
        load();
        new Thread(()->{
            try {
                while (true){
                    Thread.sleep(60000);
                    load();
                }
            } catch (Exception e) {
                Logger.error("商品类目管理器加载失败",e);
            }
        }).start();
    }

    private void load(){
        List<Category> list = categoryDao.categoryList(new HashMap<>());
        /* 获取所有父类 */
        categories = list.stream().filter(x->x.getLevel()==1).collect(Collectors.toList());
//        categories.add(0,new Category(0,"精选"));
        /* 分组子类 */
//        Map<Integer,List<Category>> child = list.stream().filter(x->x.getLevel()==2).collect(Collectors.groupingBy(Category::getPid));
        /* 组装属性类目信息 */
        childList = categories.stream().map(x->{
            Map<String,Object> map = JsonUtil.beanToMap(x);
//            if(Common.isNotEmpty(child) && Common.isNotEmpty(child.get(x.getId()))){
//                List<Map<String,Object>> mapList = new ArrayList<>();
//                mapList.add(new HashMap<String,Object>(){{
//                    put("level",1);
//                    put("name","全部");
//                    put("pid",0);
//                    put("sort",1);
//                    put("id",x.getId());
//                    put("status",1);
//                }});
//                mapList.addAll(child.get(x.getId()).stream().map(JsonUtil::beanToMap).collect(Collectors.toList()));
//                map.put("child",child.get(x.getId()).stream().map(y->{
//                    y.setIcon(Param.picUrl+y.getIcon());
//                    return JsonUtil.beanToMap(y);
//                }).collect(Collectors.toList()));
//            }
            return map;
        }).collect(Collectors.toList());
    }

    public static List<Map<String,Object>> categoryList(int level){
        return level==1?categories.stream().map(JsonUtil::beanToMap).collect(Collectors.toList()):childList;
    }
}
